// API基础URL
const BASE_API = "http://localhost:9999";

// 获取token
function getToken() {
    const token = localStorage.getItem('token');
    if (!token) {
        window.location.href = 'login.html';
        return null;
    }
    return token;
}

$(function() {
    // 检查token
    const token = getToken();
    if (!token) return;

    // 初始化图片上传区域
    initImageUpload();

    // 配置toastr提示框
    toastr.options = {
        "closeButton": true,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "timeOut": "3000"
    };

    // 加载分类列表
    function loadCategories() {
        console.log('Loading categories...');
        $.ajax({
            url: BASE_API + '/category/list',
            type: 'GET',
            headers: {'token': token},
            success: function(res) {
                console.log('Categories response:', res);
                if (res.code === 200) {
                    // 填充搜索区域的分类下拉框
                    const categorySelect = $('#categorySelect');
                    categorySelect.empty().append('<option value="">全部分类</option>');
                    
                    // 填充模态框的分类下拉框
                    const modalCategorySelect = $('#modalCategorySelect');
                    modalCategorySelect.empty().append('<option value="">请选择分类</option>');
                    
                    const categories = res.data.records || res.data;
                    categories.forEach(category => {
                        const option = `<option value="${category.id}">${category.name}</option>`;
                        categorySelect.append(option);
                        modalCategorySelect.append(option);
                    });
                } else {
                    console.error('Failed to load categories:', res.msg);
                    toastr.error(res.msg || '加载分类失败');
                }
            },
            error: function(xhr, status, error) {
                console.error('Error loading categories:', error);
                toastr.error('加载分类失败');
            }
        });
    }

    // 搜索功能实现
    let searchTimeout;

    // 搜索按钮点击事件
    $('#searchBtn').click(function() {
        const searchValue = $('#searchName').val().trim();
        loadProducts(searchValue);
    });

    // 搜索框回车��件
    $('#searchName').on('keypress', function(e) {
        if (e.which === 13) {
            const searchValue = $(this).val().trim();
            loadProducts(searchValue);
        }
    });

    // 搜索框输入事件（带防抖）
    $('#searchName').on('input', function() {
        clearTimeout(searchTimeout);
        const searchValue = $(this).val().trim();
        
        // 使用防抖，避免频繁请求
        searchTimeout = setTimeout(() => {
            loadProducts(searchValue);
        }, 300);
    });

    // 重置按钮点击事件
    $('#resetBtn').click(function() {
        $('#searchName').val('');
        $('#categorySelect').val('');
        loadProducts();
    });

    // 加载商品列表
    function loadProducts(searchValue = '') {
        const selectedCategoryId = $('#categorySelect').val();
        
        // 构建请求参数
        const params = {
            categoryId: selectedCategoryId || '',
            page: 1,
            pageSize: 1000,
            name: searchValue
        };
        
        // 显示加载状态
        $('.product-grid').empty().append('<div class="loading">加载中...</div>');
        
        // 发送请求获取商品列表
        $.ajax({
            url: BASE_API + '/product/list',
            type: 'GET',
            headers: {'token': token},
            data: params,
            success: function(res) {
                console.log('搜索结果:', res); // 添加日志
                if (res.code === 200) {
                    if (res.data && res.data.records) {
                        renderProducts(res.data.records);
                    } else {
                        $('.product-grid').html('<div class="no-data">暂无商品数据</div>');
                    }
                } else {
                    $('.product-grid').html('<div class="no-data">加载失败: ' + res.msg + '</div>');
                }
            },
            error: function(err) {
                console.error('请求错误:', err); // 添加错误日志
                $('.product-grid').html('<div class="no-data">网络错误，请稍后重试</div>');
            }
        });
    }

    // 渲染商品列表
    function renderProducts(products) {
        console.log('渲染商品:', products); // 添加日志
        
        if (!products || products.length === 0) {
            $('.product-grid').html('<div class="no-data">暂无商品数据</div>');
            return;
        }
        
        let html = '';
        products.forEach(product => {
            html += `
                <div class="product-item">
                    <div class="product-image">
                        <img src="${product.imageUrl || './static/no-image.png'}" alt="${product.name}">
                    </div>
                    <div class="product-info">
                        <div class="product-name">${product.name}</div>
                        <div class="product-price">￥${parseFloat(product.price).toFixed(2)}</div>
                        <div class="product-stock">库存: ${product.stock}</div>
                        <div class="badge ${product.status === 1 ? 'badge-success' : 'badge-warning'}">
                            ${product.status === 1 ? '已上架' : '已下架'}
                        </div>
                        <div class="product-actions">
                            <button class="btn btn-primary" onclick="editProduct(${product.id})">
                                <i class="fas fa-edit"></i> 修改
                            </button>
                            <button class="btn ${product.status === 1 ? 'btn-warning' : 'btn-success'}" 
                                onclick="updateStatus(${product.id}, ${product.status === 1 ? 0 : 1})">
                                <i class="fas fa-${product.status === 1 ? 'arrow-down' : 'arrow-up'}"></i>
                                ${product.status === 1 ? '下架' : '上架'}
                            </button>
                            <button class="btn btn-danger" onclick="deleteProduct(${product.id})">
                                <i class="fas fa-trash"></i> 删除
                            </button>
                        </div>
                    </div>
                </div>
            `;
        });
        
        $('.product-grid').empty().append(html);
    }

    // 页面加载完成后执行
    $(document).ready(function() {
        // 初始化页面
        loadCategories();  // 页面加载时就加载分类数据
        loadProducts();    // 初始加载所有商品
        
        // 监听分类选择变化
        $('#categorySelect').on('change', function() {
            const searchValue = $('#searchName').val().trim();
            loadProducts(searchValue);
        });

        // 新增按钮点击事件
        $('#addBtn').click(function() {
            clearForm();
            $('#productModal').modal('show');
        });
    });

    // 保存按钮点击事件
    $('#saveBtn').click(function() {
        if (!validateForm()) {
            return;
        }

        const productId = $('#productId').val();
        const formData = {
            id: productId || null,
            name: $('#name').val().trim(),
            categoryId: $('#modalCategorySelect').val(),
            price: parseFloat($('#price').val()),
            stock: parseInt($('#stock').val()),
            description: $('#description').val().trim(),
            imageUrl: $('#imageUrl').val(),
            status: parseInt($('#status').val())
        };

        $.ajax({
            url: BASE_API + '/product',
            type: productId ? 'PUT' : 'POST',
            headers: {
                'token': token,
                'Content-Type': 'application/json'
            },
            data: JSON.stringify(formData),
            success: function(res) {
                if (res.code === 200) {
                    $('#productModal').modal('hide');
                    toastr.success(productId ? '更新成功' : '添加成功');
                    loadProducts($('#searchName').val().trim());
                } else {
                    toastr.error(res.msg || '操作失败');
                }
            },
            error: function() {
                toastr.error('操作失败');
            }
        });
    });

    // 编辑商品
    window.editProduct = function(id) {
        $.ajax({
            url: BASE_API + '/product/' + id,
            type: 'GET',
            headers: {'token': token},
            success: function(res) {
                if (res.code === 200) {
                    // 先加载分类数据
                    $.ajax({
                        url: BASE_API + '/category/list',
                        type: 'GET',
                        headers: {'token': token},
                        success: function(categoryRes) {
                            if (categoryRes.code === 200) {
                                // 填充分类下拉框
                                const modalCategorySelect = $('#modalCategorySelect');
                                modalCategorySelect.empty().append('<option value="">请选择分类</option>');
                                const categories = categoryRes.data.records || categoryRes.data;
                                categories.forEach(category => {
                                    const option = `<option value="${category.id}">${category.name}</option>`;
                                    modalCategorySelect.append(option);
                                });
                                // 填充表单数据
                                fillForm(res.data);
                                $('#productModal').modal('show');
                            }
                        }
                    });
                } else {
                    toastr.error(res.msg || '获取商品信息失败');
                }
            },
            error: function() {
                toastr.error('获取商品信息失败');
            }
        });
    };

    // 更新商品状态
    window.updateStatus = function(id, status) {
        const confirmMsg = status === 1 ? '确认要上架该商品吗？' : '确认要下架该商品吗？';
        if (confirm(confirmMsg)) {
            $.ajax({
                url: BASE_API + '/product/status/' + status + '/' + id,
                type: 'PUT',
                headers: {'token': token},
                success: function(res) {
                    if (res.code === 200) {
                        toastr.success(status === 1 ? '商品已上架' : '商品已下架');
                        // 重新加载商品列表，保持当前的搜索条件
                        const searchValue = $('#searchName').val().trim();
                        loadProducts(searchValue);
                    } else {
                        toastr.error(res.msg || '操作失败');
                    }
                },
                error: function() {
                    toastr.error('操作失败');
                }
            });
        }
    };

    // 删除商品
    window.deleteProduct = function(id) {
        if (confirm('确认要删除该商品吗？此操作不可恢复！')) {
            $.ajax({
                url: BASE_API + '/product/' + id,
                type: 'DELETE',
                headers: {'token': token},
                success: function(res) {
                    if (res.code === 200) {
                        toastr.success('删除成功');
                        loadProducts($('#categorySelect').val());
                    } else {
                        toastr.error(res.msg || '删除失败');
                    }
                },
                error: function() {
                    toastr.error('删除失败');
                }
            });
        }
    };

    // 表单验证
    function validateForm() {
        const categoryId = $('#modalCategorySelect').val();
        const name = $('#name').val();
        const price = $('#price').val();
        const stock = $('#stock').val();

        if (!categoryId) {
            toastr.error('请选择商品分类');
            return false;
        }
        if (!name) {
            toastr.error('请输入商品名称');
            return false;
        }
        if (!price || price <= 0) {
            toastr.error('请输入正确的商品价格');
            return false;
        }
        if (!stock || stock < 0) {
            toastr.error('请输入正确的库存数量');
            return false;
        }
        return true;
    }

    // 清空表单
    function clearForm() {
        $('#productForm')[0].reset();
        $('#productId').val('');
        $('#imageUrl').val('');
        $('#imagePreview').attr('src', '');
        $('.preview-container').hide();
        $('#uploadArea').show();
    }

    // 填充表单
    function fillForm(data) {
        console.log('Filling form with data:', data); // 添加日志
        $('#productId').val(data.id);
        $('#modalCategorySelect').val(data.categoryId);
        $('#name').val(data.name);
        $('#price').val(data.price);
        $('#stock').val(data.stock);
        $('#description').val(data.description);
        $('#status').val(data.status);

        if (data.imageUrl) {
            $('#imageUrl').val(data.imageUrl);
            $('#imagePreview').attr('src', data.imageUrl);
            $('.preview-container').show();
            $('#uploadArea').hide();
        } else {
            $('#imageUrl').val('');
            $('#imagePreview').attr('src', '');
            $('.preview-container').hide();
            $('#uploadArea').show();
        }
        
        // 确保分类值被正确设置
        setTimeout(() => {
            const categoryId = data.categoryId;
            const categorySelect = $('#modalCategorySelect');
            if (categoryId && categorySelect.find(`option[value="${categoryId}"]`).length) {
                categorySelect.val(categoryId);
            }
        }, 100);
    }

    // 初始化图片上传
    function initImageUpload() {
    const uploadArea = $('#uploadArea');
    const fileInput = $('#imageFile');
    const imagePreview = $('#imagePreview');
        const previewContainer = $('.preview-container');
        const removeButton = $('#removeImage');
    const progressBar = $('.progress-bar');
    const progressText = $('.progress-text');
        const uploadProgress = $('.upload-progress');

        uploadArea.click(function() {
            fileInput.click();
        });

        uploadArea.on('dragover', function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).addClass('dragover');
    });

        uploadArea.on('dragleave', function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).removeClass('dragover');
    });

    uploadArea.on('drop', function(e) {
        e.preventDefault();
        e.stopPropagation();
            $(this).removeClass('dragover');
            
        const files = e.originalEvent.dataTransfer.files;
        if (files.length > 0) {
            handleFile(files[0]);
        }
    });

        fileInput.change(function() {
            if (this.files.length > 0) {
                handleFile(this.files[0]);
            }
        });

        removeButton.click(function() {
            clearImage();
        });

    function handleFile(file) {
            if (!file.type.match('image.*')) {
                toastr.error('请选择图片文件');
            return;
        }

            if (file.size > 5 * 1024 * 1024) {
            toastr.error('图片大小不能超过5MB');
            return;
        }

        uploadProgress.show();
        progressBar.css('width', '0%');
        progressText.text('0%');

            const formData = new FormData();
            formData.append('file', file);

        $.ajax({
            url: BASE_API + '/common/fileUpload',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
                headers: {'token': token},
            xhr: function() {
                    const xhr = new window.XMLHttpRequest();
                xhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        const percent = Math.round((e.loaded / e.total) * 100);
                        progressBar.css('width', percent + '%');
                        progressText.text(percent + '%');
                    }
                    }, false);
                return xhr;
            },
            success: function(res) {
                if (res.code === 200) {
                        imagePreview.attr('src', res.data);
                        previewContainer.show();
                        uploadArea.hide();
                        $('#imageUrl').val(res.data);
                    toastr.success('上传成功');
                } else {
                    toastr.error(res.msg || '上传失败');
                }
            },
            error: function() {
                toastr.error('上传失败');
            },
            complete: function() {
                    uploadProgress.hide();
            }
        });
    }

        function clearImage() {
            imagePreview.attr('src', '');
            previewContainer.hide();
            uploadArea.show();
            $('#imageUrl').val('');
            fileInput.val('');
        }
    }
});